package com.hjy.core.provider;

import com.hjy.common.enumeration.RpcError;
import com.hjy.common.exception.RpcException;

import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultServiceProvider implements ServiceProvider {
    /**
     * 全限定类名: 服务对象
     */
    private static final Map<String, Object> serviceMap = new ConcurrentHashMap<>();

    /**
     * 用于判重
     */
    private static final Set<String> registerService = ConcurrentHashMap.newKeySet();

    @Override
    public <T> void register(T service) {
        // 获取全类名
        String serviceName = service.getClass().getCanonicalName();
        if (registerService.contains(serviceName)) return;
        registerService.add(serviceName);
        Class<?>[] interfaces = service.getClass().getInterfaces();
        if (interfaces.length == 0) {
            // 注册的服务未实现接口
            throw new RpcException(RpcError.SERVICE_NOT_IMPLEMENT_ANY_INTERFACE);
        }
        for (Class<?> i : interfaces) {
            serviceMap.put(i.getCanonicalName(), service);
        }
        System.out.println("向接口: " + Arrays.toString(interfaces) + " 注册服务: " + serviceName);
    }

    @Override
    public Object getService(String serviceName) {
        Object service = serviceMap.get(serviceName);
        if (service == null) {
            // 找不到对应的服务
            return new RpcException(RpcError.SERVICE_NOT_FOUND);
        }
        return service;
    }
}
